package demo4.service;

import com.tedu.InputUtil;
import demo4.mapper.IUserMapper;
import demo4.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

@Component
public class UserService {
    @Autowired
    private IUserMapper userMapper;

    public void register() {
        User user = InputUtil.getInputObject(new User(), "请输入注册信息：");
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            System.out.println("该用户已存在!!!");
        } else {
            try {
                int num = userMapper.insert(user);
                System.out.println(num > 0 ? "好耶，注册成功咯！" : "啊哦，注册失败了...");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void login() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入登录信息：");
        System.out.println("请输入用户名：");
        String userName = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        if (userMapper.selectByUsername(userName) == null) {
            System.out.println("用户名不正确！");
        } else {
            userMapper.select(userName, password);
        }
    }

    public void updateUser() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String userName = sc.nextLine();
        if (userMapper.selectByUsername(userName) == null) {
            System.out.println("用户名不存在，无法修改！");
            System.exit(0);//正常退出程序
        }
        System.out.println("请输入修改信息：");
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        System.out.println("请输入昵称：");
        String nickname = sc.nextLine();
        System.out.println("请输入年龄：");
        Integer age = Integer.parseInt(sc.nextLine());
        User user = new User(null, userName, password, nickname, age);
        int num = userMapper.update(user);
        System.out.println(num > 0 ? "好耶，信息修改成功咯！" : "啊哦，信息修改失败了...");
    }

    public void listUser(){
        List<User> list = userMapper.selectAll();
        System.out.println("用户列表：");
        for(User user : list){
            System.out.println(user);
        }
    }

    public void deleteUser(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要删除的用户名：");
        String userName = sc.nextLine();
        if(userMapper.selectByUsername(userName) == null){
            System.out.println("用户名不存在，无法再删除！");
        }else {
            userMapper.deleteByUsername(userName);
        }
    }
}

